package com.smart.business.controller;

import com.smart.aop.log.LogType;
import com.smart.aop.log.SaveLog;
import com.smart.aop.permission.HasPermission;
import com.smart.business.dao.LocalDictDao;
import com.smart.business.service.pointServiceImpl;
import com.smart.common.utils.DateUtil;
import com.smart.entity.business.CompanyDataEntity;
import com.smart.entity.export.*;
import com.smart.model.excel.annotation.ExcelField;
import com.smart.model.exception.SmartException;
import com.smart.model.response.r.Result;
import com.smart.model.response.r.ResultCode;
import com.smart.model.response.r.ResultWrapper;
import com.smart.service.business.CompanyDataService;
import com.smart.tools.excel.ExcelExport;
import com.smart.tools.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公司1 Controller
 *
 * @author wf
 * @since 2025-07-21 13:06:18
 */
@RestController
@RequestMapping("/business/companyData")
public class CompanyDataController {
    @Autowired
    CompanyDataService companyDataService;
    @Autowired
    ResultWrapper resultWrapper;
    @Autowired
    private pointServiceImpl pointService;
    @Autowired
    private LocalDictDao localDictDao;

    /**
     * 列表
     *
     * @param companyDataEntity 公司1bean
     * @return String
     */
    @GetMapping("/page")
    public String page(CompanyDataEntity companyDataEntity) {
        return Result.data(companyDataService.findPage(companyDataEntity));
    }

    /**
     * 列表（不分页）
     *
     * @param companyDataEntity 公司1bean
     * @return String
     */
    @GetMapping("/list")
    public String list(CompanyDataEntity companyDataEntity) {
        return Result.data(companyDataService.findList(companyDataEntity));
    }

    /**
     * 信息
     *
     * @param id 主键ID
     * @return String
     */
    @GetMapping("/get")
    public String get(@RequestParam String id) {
        CompanyDataEntity result = companyDataService.get(id);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 保存
     *
     * @param companyDataEntity 公司1bean
     * @return String
     */
    @HasPermission("companyData:add")
    @PostMapping("/save")
    @SaveLog(module = "公司1管理" , type = LogType.ADD)
    public String save(@RequestBody CompanyDataEntity companyDataEntity) {
        CompanyDataEntity result = companyDataService.saveEntity(companyDataEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 修改
     *
     * @param companyDataEntity 公司1bean
     * @return String
     */
    @HasPermission("companyData:update")
    @PostMapping("/update")
    @SaveLog(module = "公司1管理" , type = LogType.UPDATE)
    public String update(@RequestBody CompanyDataEntity companyDataEntity) {
        CompanyDataEntity result = companyDataService.updateEntity(companyDataEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 删除
     *
     * @param companyDataEntity 公司1bean
     * @return String
     */
    @HasPermission("companyData:delete")
    @PostMapping("/delete")
    @SaveLog(module = "公司1管理" , type = LogType.DELETE)
    public String delete(@RequestBody CompanyDataEntity companyDataEntity) {
        return Result.status(companyDataService.delete(companyDataEntity));
    }

    /**
     * 导出
     *
     * @param pointId 公司1bean
     * @param response 响应
     */
    @HasPermission("companyData:export")
    @PostMapping(value = "/export")
    public void exportData(@RequestParam(required = false) String pointId,
                           @RequestParam(required = false) String startTime,
                           @RequestParam(required = false) String endTime,
                           @RequestParam(required = false) String frequency,
                           @RequestParam(defaultValue = "1") int current,
                           @RequestParam(defaultValue = "10") int size,
                           HttpServletResponse response) {
        // 创建公司类型与实体类的映射
        Map<String, Class<?>> entityClassMap = new HashMap<>();
        entityClassMap.put("sys_company_1_1", SysCompany11.class);
        entityClassMap.put("sys_company_1_2", SysCompany12.class);
        entityClassMap.put("sys_company_1_3", SysCompany13.class);
        entityClassMap.put("sys_company_1_4", SysCompany14.class);
        entityClassMap.put("sys_company_2_1", SysCompany21.class);
        Map<String, Object> resultMap = pointService.getList(pointId, startTime, endTime, frequency, current, size);
        Map<String,List<?>> pointMap = (Map<String,List<?>>)resultMap.get("list");
        String  companyType= (String) resultMap.get("tableName");
        // 根据公司类型获取对应的实体类
        Class<?> entityClass;
        if (frequency != null){
            entityClass = CpConsumption.class;
        }else {
            entityClass = entityClassMap.get(companyType);
        }
        List<?> resultList = pointMap.values().stream()
                .filter(list -> list != null && !list.isEmpty())
                .flatMap(List::stream)
                .collect(Collectors.toList());
        String tableName = localDictDao.getCompanyName(companyType);
        if (tableName == null) {
            throw new SmartException("未找到公司类型！");
        }

        List<?> list = resultWrapper.setListIdentityInfo(resultList,entityClass);
        String fileName = companyType + "数据" + DateUtil.getDate("yyyyMMddHHmmss") + ".xlsx";
        try (ExcelExport export = new ExcelExport(tableName, entityClass)) {
            export.setDataList(list).write(response, fileName);
        }
    }

    /**
     * 导入
     *
     * @param request 请求
     */
    @HasPermission("companyData:import")
    @PostMapping(value = "/import")
    public String importData(MultipartHttpServletRequest request) {
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        List<MultipartFile> files = multiFileMap.get("files");
        try (ExcelImport excelImport = new ExcelImport(files.get(0), 2, 0)) {
            List<CompanyDataEntity> dataList = excelImport.getDataList(CompanyDataEntity.class);
            return Result.status(companyDataService.saveBatch(dataList));
        } catch (Exception e) {
            return Result.fail("导入失败！");
        }
    }

    /**
     * 下载导入模板
     *
     * @param response 响应
     */
    @GetMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "导入公司1模板.xlsx";
        try (ExcelExport export = new ExcelExport("公司1数据", CompanyDataEntity.class, null, ExcelField.Type.IMPORT)) {
            export.write(response, fileName);
        }
    }


}
